<script lang="ts" setup>
import { deleteDevice, setDeviceStatus } from '@/api/device';
import type { device, devices } from '@/props/device';
import { useDeviceStore } from '@/stores/device';
import { Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { ref, computed, reactive, watch } from 'vue';

const deviceStore = useDeviceStore()

const devicesData = reactive<devices>([])

// 获取数据
function getRandomFloat(min:number, max:number) {
  return +(Math.random() * (max - min) + min).toFixed(1);
}


watch(() => deviceStore.deviceAllData, (newData) => {
  // 清空当前的 devicesData
  devicesData.splice(0, devicesData.length);

  // 将 newData 的内容添加到 devicesData 中，并同时转换 status 属性
  newData.forEach((item) => {
    // 如果是 deviceType 类型为 1 的项，则跳过
    if (item.deviceType === 1) return;

    // 创建一个新的对象，以确保我们不会修改原始数据
    const newItem = { ...item, status: item.status === 1 };

    // 根据 deviceType 设置 icon
    if (item.deviceType === 0) {
      newItem['icon'] = '/src/assets/device/tableLamp.png';
    } else if (item.deviceType === 2) { // 注意：这里假设除了'0'和'1'外还有其他类型
      newItem['icon'] = '/src/assets/device/fan.png';
    }

    // 添加随机生成的 kwh 和 activeTime 值
    newItem['kwh'] = getRandomFloat(5, 40);
    newItem['activeTime'] = getRandomFloat(0, 24);

    // 因为我们已经清空了 devicesData，所以只需要 push 新项
    devicesData.push(newItem);
  });
}, { deep: true }); // 确保深度监听，如果 deviceAllData 是一个复杂对象

// const devices = reactive([
//   {
//     name: 'Smart TV',
//     icon: 'https://placehold.co/50?text=TV',
//     usage: 5,
//     active: false,
//     activeTime: 3,
//   },
// ]);

const currentPage = ref(1);
const itemsPerPage = 6;

const totalPages = computed(() => Math.ceil(devicesData.length / itemsPerPage));

const currentDevices = computed(() => {
  const start = (currentPage.value - 1) * itemsPerPage;
  const end = start + itemsPerPage;
  return devicesData.slice(start, end);
});

//设备状态修改
const setDeviceStatusData = async(deviceId:number,status:number) => {
  const {data} =  await setDeviceStatus(deviceId,status)
  if (data.code === 1) {
    deviceStore.dialogDeivce += 1
    ElMessage.success("状态修改成功")
    return
  }
  ElMessage.error(`状态修改失败${data.msg}`)
}
function handleSwitchChange(device:device) {
  const status = device.status?1:0
  setDeviceStatusData(device.deviceId,status)
}

function prevPage() {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
}

function nextPage() {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
  }
}

//删除设备
const deleteData = reactive<{
  deviceName:string,
  deviceId: number | null;
  deviceType: number | null;
}>({
  deviceName:'',
  deviceId: null,
  deviceType: null
});
const buttonClick = (deviceName:string,deviceId:number,deviceType:number) => {
  dialogVisible.value=true
  deleteData.deviceName = deviceName
  deleteData.deviceId = deviceId
  deleteData.deviceType = deviceType
}

const deleteDeviceData = async () => {
  if (deleteData.deviceId !== null && deleteData.deviceType !== null) {
    try {
      const { data } = await deleteDevice(deleteData.deviceId, deleteData.deviceType);
      if (data.code === 1) {
        ElMessage.success("设备删除成功");

        // 移除 devicesData 中对应的设备
        const index = devicesData.findIndex(d => d.deviceId === deleteData.deviceId);
        if (index !== -1) {
          devicesData.splice(index, 1);
        }
        dialogVisible.value = false;
      } else {
        ElMessage.error("设备删除失败");
      }
    } catch (error) {
      console.log(error)
    }
  } else {
    ElMessage.error("设备不存在");
  }
};

const dialogVisible = ref(false)
</script>

<template>
  <div>
    <div class="usage-status-chart">
      <el-dialog v-model="dialogVisible" :modal="false"  width="500">
        <span>是否删除 {{ deleteData.deviceName }} 设备</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="dialogVisible = false">取消</el-button>
            <el-button type="danger" @click="deleteDeviceData">
              确认
            </el-button>
          </div>
        </template>
      </el-dialog>

    <div v-for="(device, index) in currentDevices" :key="index" class="device-item">

      <el-row :gutter="20">
        <el-col :span="6">
          <img :src="device.icon" alt="" class="device-icon" />
        </el-col>
        <el-col :span="18">
          <div class="device-name">{{ device.deviceName }}</div>
          <div class="device-status">
            <el-switch
              v-model="device.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="handleSwitchChange(device)"
            ></el-switch>
            <span>{{ device.kwh }}Kwh</span>

            <el-button type="danger" @click="buttonClick(device.deviceName,device.deviceId,device.deviceType)" :icon="Delete" circle />
          </div>
          <div class="device-active-time">Active for {{ device.activeTime }} hours</div>
        </el-col>
      </el-row>
    </div>
  </div>
      <!-- 分页按钮 -->
    <div class="pagination" v-if="devicesData.length > 0">
      <el-button type="primary" class="transparent-bg" @click="prevPage" :disabled="currentPage === 1">Previous</el-button>
      <el-button type="primary" class="transparent-bg" @click="nextPage" :disabled="currentPage === totalPages">Next</el-button>
    </div>
  </div>

</template>

<style lang="scss" scoped>
.transparent-bg {
  margin-top: 5%;
  background: transparent !important;
}

:deep(.el-dialog) {
  background-color: rgb(47, 59, 82);
}


.usage-status-chart {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  background: black;

  .device-item {
    color: white;

    padding: 20px !important;
    border: 1px solid rgb(51, 51, 51);
    .device-icon {
      width: 40px;
      height: 40px;
    }

    .device-name {
      font-size: 16px;
      margin-bottom: 10px;
    }

    .device-status {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .el-switch__core {
        width: 40px !important;
        height: 20px !important;
      }
      .el-button{
        background: black;
        border: 1px solid rgb(94, 94, 94);
      }
      .el-button:hover{
        border: 1px solid rgb(143, 52, 52);
      }
    }

    .device-active-time {
      font-size: 12px;
      margin-top: 10px;
    }
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
